<template>
  <div class="image-upload-component">
    <a-upload
      v-model:file-list="fileList"
      list-type="picture-card"
      :show-upload-list="true"
      :before-upload="beforeUpload"
      @change="handleChange"
      :custom-request="customUpload"
      :multiple="multiple"
      :max-count="maxCount"
    >
      <div v-if="fileList.length < maxCount" class="upload-placeholder">
        <PlusOutlined />
        <div style="margin-top: 8px">{{ placeholderText }}</div>
      </div>
    </a-upload>
    
    <div v-if="showTips" class="upload-tips">
      <!-- <p>• 建议尺寸：{{ recommendedSize }}</p> -->
      <p v-if="multiple">手机、电脑截图最佳，可上传 {{ maxCount }} 张图片，仓库、特情处、总资产为必须</p>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, computed } from 'vue'
import { message } from 'ant-design-vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import uploadAPI from '~/api/upload'
import { useUserStore } from '~/stores/user'

// Props
const props = defineProps({
  value: {
    type: [String, Array],
    default: () => []
  },
  placeholderText: {
    type: String,
    default: '上传图片'
  },
  recommendedSize: {
    type: String,
    default: '电脑、手机截图都行'
  },
  showTips: {
    type: Boolean,
    default: true
  },
  maxSize: {
    type: Number,
    default: 5 // MB
  },
  multiple: {
    type: Boolean,
    default: true
  },
  maxCount: {
    type: Number,
    default: 5
  }
})

// Emits
const emit = defineEmits(['update:value', 'change', 'login-required'])

// 用户store
const userStore = useUserStore()

// 响应式数据
const fileList = ref([])

// 计算属性：处理value的格式
const imageUrls = computed(() => {
  if (Array.isArray(props.value)) {
    return props.value
  } else if (typeof props.value === 'string' && props.value) {
    return [props.value]
  }
  return []
})

// 监听value变化，同步到fileList
watch(() => props.value, (newValue) => {
  if (Array.isArray(newValue)) {
    fileList.value = newValue.map((url, index) => ({
      uid: `image-${index}`,
      name: `image-${index}.jpg`,
      status: 'done',
      url: url,
      thumbUrl: url
    }))
  } else if (typeof newValue === 'string' && newValue) {
    fileList.value = [{
      uid: 'image-0',
      name: 'image-0.jpg',
      status: 'done',
      url: newValue,
      thumbUrl: newValue
    }]
  } else {
    fileList.value = []
  }
}, { immediate: true })

// 上传前验证
const beforeUpload = (file) => {
  // 检查登录状态
  if (!userStore.isLoggedIn) {
    message.warning('请先登录后再上传图片')
    emit('login-required')
    return false
  }

  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
  if (!isJpgOrPng) {
    message.error('只能上传 JPG/PNG 格式的图片!')
    return false
  }
  
  const isLtMaxSize = file.size / 1024 / 1024 < props.maxSize
  if (!isLtMaxSize) {
    message.error(`图片大小不能超过 ${props.maxSize}MB!`)
    return false
  }

  // 检查数量限制
  if (props.multiple && fileList.value.length >= props.maxCount) {
    message.error(`最多只能上传 ${props.maxCount} 张图片!`)
    return false
  }
  
  return true
}

// 自定义上传
const customUpload = async ({ file, onSuccess, onError }) => {
  try {
    // 再次检查登录状态
    if (!userStore.isLoggedIn) {
      message.error('请先登录后再上传图片')
      emit('login-required')
      onError()
      return
    }

    // 用统一API封装
    const { urls } = await uploadAPI.uploadScreenshots(file);
    if (urls && urls.length > 0) {
      const url = urls[0];
      
      // 获取已有的图片URLs（排除当前正在上传的文件）
      const existingUrls = fileList.value
        .filter(f => f.status === 'done' && f.url)
        .map(f => f.url);
      
      // 添加新上传的URL
      const allUrls = [...existingUrls, url];
      
      // 发送更新事件
      emit('update:value', props.multiple ? allUrls : url);
      emit('change', props.multiple ? allUrls : url);
      onSuccess({ url });
    } else {
      message.error('上传失败');
      onError();
    }
  } catch (error) {
    console.error('Upload error:', error);
    message.error('上传失败，请重试');
    onError();
  }
};

// 处理变化（包括删除）
const handleChange = (info) => {
  console.log('handleChange:', info.file.status, info.fileList.length)
  
  if (info.file.status === 'uploading') {
    return
  }
  
  if (info.file.status === 'done') {
    // 上传完成后的处理已在customUpload中完成
    return
  }
  
  if (info.file.status === 'removed') {
    // 处理删除 - 获取剩余文件的URLs
    const remainingUrls = info.fileList
      .filter(f => f.status === 'done' && f.url)
      .map(f => f.url)
    
    console.log('删除后剩余URLs:', remainingUrls)
    emit('update:value', props.multiple ? remainingUrls : (remainingUrls[0] || ''))
    emit('change', props.multiple ? remainingUrls : (remainingUrls[0] || ''))
  }
}
</script>

<style scoped>
.image-upload-component {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #999;
  font-size: 14px;
}

.upload-tips {
  color: #666;
  font-size: 12px;
}

.upload-tips p {
  margin-bottom: 4px;
}

</style> 